$(document).ready(function() {
	LanguageChanger.init();
	Tooltip.init();
	SearchBar.init();
});

/**
 * SearchBar
 */
SearchBar = {};

SearchBar.init = function() {
	$('#searchInput').keypress(function(e) {
        if(e.which == 13) {
            $(this).blur();
            SearchBar.submitSearch();
        }
    });
	$('#searchInputButton').click(function(e){
		SearchBar.submitSearch();
	});
	$("#searchInput").autocomplete({
		source : "/ajax/itemSearch",
		minLength : 2,
		select : function(event, ui) {
			window.location = "/item/" + ui.item.id;
			return true;
		},
		search: function( event, ui ) {
			SearchBar.cloudSearch(event.target.value);
		}
	});
}

SearchBar.runningCloudSearch = false;
SearchBar.cloudSearch = function(val){
	

	
	$.ajax({
		url : '/ajax/ajaxWordCloud',
		type : "POST",
		data : {
		    query : val,
		    limit : '6'
		}
	}).done(function(data){
		
		if(data.length > 0){

			var s = "";
			for(var i = 0; i < data.length; i++){
				
					s = s + "<a href=\"/search?query="+data[i]+"\">"+data[i]+"</a>";
					if(i != (data.length-1)){
						s = s + ", ";

					}
				
			}
			$('#partnerWordCloud').html('<br>Maybe you are interested in: '+s+' ?');	
	

		}
		
	});
}

SearchBar.submitSearch = function(){
	var query = $('#searchInput').val().trim();
	if(query != '')
		Util.redirect('/search?query='+query);
}


/**
 * Language Changer
 */

LanguageChanger = {};

LanguageChanger.init = function() {
	$('#languageDropdown').change(function(e) {
		LanguageChanger.onChange();
	});
}

LanguageChanger.onChange = function() {
	var parameters = Util.getURLParameters($(location).attr('href'));
	parameters['locale'] = $('#languageDropdown').val();
	var url = $(location).attr('href').replace(/[\?#].*/, '') + '?'
			+ decodeURIComponent($.param(parameters))
			+ $(location).attr('hash');
	Util.redirect(url);
}

/**
 * Tooltip
 */
Tooltip = {};

Tooltip.init = function() {
	$(document).tooltip({
		show : false,
		hide : false,
		position : {
			at: "right+3 top-15",
		    collision: "fit"
		}
	});
}

/**
 * Utilities
 */
Util = {};

Util.redirect = function(url) {
	window.location.href = url
}

Util.getURLParameters = function(url) {
	var vars = {};
	var parts = url.replace(/[?&]+([^=&#]+)=([^&#]*)/gi,
			function(m, key, value) {
				vars[key] = value;
			});
	return vars;
}

//Because JavaScript IsNumeric means whitespace is a number... 
Util.isNumber = function(n) {
	return !isNaN(parseFloat(n)) && isFinite(n);
}

function getURLParameter(name) {
    return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null;
}